import { toFail, toSuccess, useRedis } from "@sker/core";
import { useData } from "@sker/runtime";
import { RedisClientType } from "redis";
import { z } from "zod";

import axios from "axios";
import dayjs from "dayjs";
import request from 'superagent';
require('superagent-proxy')(request)

function get(targetUrl: string, ipJson: any) {
    return new Promise<string>((resolve, reject) => {
        const { ip, port, user, pass } = ipJson;
        const proxyServer = `${user}:${pass}@${ip}:${port}`
        const proxyUrl = `http://${proxyServer}`;
        (request as any).get(targetUrl)
            .proxy(proxyUrl)
            .then(res => {
                resolve(res.request.url);
            }).catch(err => {
                reject(err);
            });
    })
}

export default async () => {
    const input = z.object({
        url: z.string(),
    });
    const body = input.parse(useData())
    let result: any;
    const call = async (r: RedisClientType)=>{
        let ipJson = await getCacheIp(r);
        if (!ipJson) {
            ipJson = await getCacheIp(r);
            return;
        }
        try {
            const url = await get(body.url, ipJson)
            const [path, query] = url.split(`?`)
            const res = path.match(/fw\/live\/(.*)/)
            if (res && res.length > 0) {
                const [, ksid] = res;
                const params: any = {}
                query.split('&').map(key => {
                    const [name, value] = key.split('=');
                    params[name] = value;
                });
                result = { ...params, ksid };
            }
        } catch (e) {
            console.error(e)
        }
    }
    await useRedis(4, async r => {
        await call(r)
    })
    if (result) {
        return toSuccess(result)
    } else {
        return toFail(`获取失败`)
    }
}

async function getCacheIp(r: RedisClientType) {
    const ipKeys = await r.keys('ip_*')
    if (ipKeys && ipKeys.length > 0) {
        const key = ipKeys[0];
        const ipStr = await r.get(key);
        const ipJson = JSON.parse(ipStr);
        return ipJson;
    }
    try {
        return await getIp(r)
    } catch (e) {
        console.error(e.message)
    }
}
async function getIp(r: RedisClientType) {
    // http://sd.jghttp.alicloudecs.com/get_ip?num=1&type=2&pro=&city=0&yys=0&port=11&time=6&ts=0&ys=0&cs=0&lb=1&sb=0&pb=45&mr=1&regions=
    const url = `http://sd.jghttp.alicloudecs.com/get_ip?num=1&type=2&pro=&city=0&yys=0&port=2&time=9&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=`
    const data = await axios.get(url).then(res => res.data)
    if (data.code === 0) {
        const ips: any[] = data.data
        if (ips && ips.length > 0) {
            ips.map(ip => {
                const key = `ip_${ip.ip}`
                r.set(key, JSON.stringify(ip));
                const exip = Math.floor((dayjs(ip.expire_time, 'YYYY-MM-DD HH:mm:ss').toDate().getTime() - dayjs().toDate().getTime()) / 1000);
                r.expire(key, exip)
            });
            return ips[0];
        }
    }
}